
import unittest
import logging

from b2v import *

dt=[
    ['id', 3],
    ['len', 12],
    ['prop', 9]
]

b=b2v(dt)
data = [0x12, 0x34, 0x56, 0x78, 0x9a]
ndata = [0]*8

iot=[
    ['dir_forward', 1],
    ['dir_backward', 1],
    ['ato_start', 1],
    ['door_status', 1],
    ['ldoor_open_btn', 1],
    ['rdoor_open_btn', 1],
    ['ldoor_close_btn', 1],
    ['rdoor_close_btn', 1],
]

iob=b2v(iot)

byt=[
    ['id', 1],
    ['len', 2],
    ['prop', 3],
    ['data', 4],
]

byb=b2v(byt)

class test_b2v(unittest.TestCase):
    def test_get_bits(self):
        self.assertEqual(0x01, b.get_bits(data, 4))
        self.assertEqual(0x12, b.get_bits(data, 8))
        self.assertEqual(0x1234, b.get_bits(data, 16))
        self.assertEqual(0x12345678, b.get_bits(data, 32))
        self.assertEqual(0x23456789, b.get_bits(data, 32, 4))

    def test_make_bits(self):
        self.assertEqual([0x12, 0x30], b.make_bits(ndata, 0, 0x123, 12))
        self.assertEqual([0x48, 0xD0], b.make_bits(ndata, 0, 0x1234, 14))
        self.assertEqual([0x12, 0x34], b.make_bits(ndata, 0, 0x1234, 16))
        ndata[0] = 0xc0
        self.assertEqual([0xc1, 0x23], b.make_bits(ndata, 4, 0x123, 12))
        ndata[0] = 0x80
        self.assertEqual([0x81, 0x23], b.make_bits(ndata, 4, 0x123, 12))
        ndata[0] = 0x80
        self.assertEqual([0x81, 0x1f, 0xe0], b.make_bits(ndata, 7, 0x8ff, 12))

    def test_var2stream(self):
        bstr = [0]*4
        b.id = 1
        b.len = 1
        b.prop = 1
        b.var_to_stream(bstr)
        self.assertEqual([0x20, 0x02, 0x01], bstr[0:3])
    
    def test_stream2var(self):
        cdata = [0x20, 0x02, 0x01]
        b.stream_to_var(cdata)
        self.assertEqual([1, 1, 1], [b.id, b.len, b.prop])

    def test_io_s2v(self):
        iob.stream_to_var([0x55])
        self.assertEqual(
            [0, 1, 0, 1], 
            [iob.dir_forward, iob.dir_backward, iob.ato_start, iob.door_status])

    def test_byb_bytes2v(self):
        byb.bytes_to_var([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xFF, 0x55, 0xAA])
        self.assertEqual(0x12, byb.id)
        self.assertEqual(0x3456, byb.len)
        self.assertEqual(0x789ABC, byb.prop)
        self.assertEqual(0xDEFF55AA, byb.data)

if __name__ == "__main__":
    unittest.main()        
